/**
 * 亲戚称呼换算工具应用主逻辑
 */
document.addEventListener('DOMContentLoaded', function() {
    // DOM元素
    const relationSelect = document.getElementById('relationSelect');
    const addRelationBtn = document.getElementById('addRelation');
    const clearRelationsBtn = document.getElementById('clearRelations');
    const calculateBtn = document.getElementById('calculate');
    const relationChain = document.getElementById('relationChain');
    const resultRelation = document.getElementById('resultRelation');
    const resultChain = document.getElementById('resultChain');
    const commonRelationsContainer = document.getElementById('commonRelations');
    
    // 当前关系路径
    let currentRelations = [];
    
    // 事件监听器
    addRelationBtn.addEventListener('click', addRelation);
    clearRelationsBtn.addEventListener('click', clearRelations);
    calculateBtn.addEventListener('click', calculateRelationship);
    
    // 初始化常见关系
    initCommonRelations();
    
    /**
     * 添加关系到关系链
     */
    function addRelation() {
        const selectedRelation = relationSelect.value;
        
        if (!selectedRelation) {
            alert('请选择一个关系');
            return;
        }
        
        // 添加到关系数组
        currentRelations.push(selectedRelation);
        
        // 更新UI
        updateRelationChain();
        
        // 重置选择框
        relationSelect.value = '';
    }
    
    /**
     * 更新关系链显示
     */
    function updateRelationChain() {
        // 清空现有链（除了"我"）
        while (relationChain.children.length > 1) {
            relationChain.removeChild(relationChain.lastChild);
        }
        
        // 添加每个关系
        for (const relation of currentRelations) {
            // 创建箭头元素
            const arrowEl = document.createElement('div');
            arrowEl.className = 'relation-arrow';
            arrowEl.textContent = '→';
            relationChain.appendChild(arrowEl);
            
            // 创建关系元素
            const relationEl = document.createElement('div');
            relationEl.className = 'relation-item';
            
            const labelEl = document.createElement('span');
            labelEl.className = 'relation-label';
            labelEl.textContent = RelationEngine.getRelationText(relation);
            
            relationEl.appendChild(labelEl);
            relationChain.appendChild(relationEl);
        }
    }
    
    /**
     * 清空关系链
     */
    function clearRelations() {
        currentRelations = [];
        updateRelationChain();
        resultRelation.textContent = '-';
        resultChain.textContent = '';
        if (document.getElementById('resultExplanation')) {
            document.getElementById('resultExplanation').innerHTML = '';
        }
    }
    
    /**
     * 计算亲戚关系
     */
    function calculateRelationship() {
        const result = RelationEngine.calculateRelation(currentRelations);
        
        resultRelation.textContent = result.call || '未知关系';
        
        // 构建关系链描述
        let chainDescription = '';
        if (currentRelations.length > 0) {
            chainDescription = '我';
            for (const relation of currentRelations) {
                chainDescription += ' → ' + RelationEngine.getRelationText(relation);
            }
        }
        resultChain.textContent = chainDescription;
        
        // 显示推导过程和解释
        showExplanation(result);
    }
    
    /**
     * 显示关系推导解释
     * @param {Object} result - 计算结果对象
     */
    function showExplanation(result) {
        // 检查结果部分是否有解释区域，如果没有则创建
        let explanationEl = document.getElementById('resultExplanation');
        if (!explanationEl) {
            explanationEl = document.createElement('div');
            explanationEl.id = 'resultExplanation';
            explanationEl.className = 'result-explanation';
            document.querySelector('.result').appendChild(explanationEl);
        }
        
        // 构建解释内容
        let explanationHTML = '<h3>关系推导</h3>';
        
        // 添加关系类型信息
        if (result.relationType) {
            explanationHTML += `<p><strong>关系类型：</strong>${result.relationType}</p>`;
        }
        
        // 添加解释
        if (result.explanation) {
            explanationHTML += `<p><strong>解释：</strong>${result.explanation}</p>`;
        }
        
        // 如果有简化路径，显示简化过程
        if (result.originalPath && result.simplifiedPath) {
            explanationHTML += `<p><strong>关系简化：</strong>从<span class="original-path">${result.originalPath.map(key => RelationEngine.getRelationText(key)).join('的')}</span>简化为<span class="simplified-path">${result.simplifiedPath.map(key => RelationEngine.getRelationText(key)).join('的')}</span></p>`;
        }
        
        explanationEl.innerHTML = explanationHTML;
    }
    
    /**
     * 初始化常见关系展示
     */
    function initCommonRelations() {
        const commonRelations = RelationEngine.getCommonRelations();
        
        commonRelationsContainer.innerHTML = '';
        
        for (const relation of commonRelations) {
            const itemEl = document.createElement('div');
            itemEl.className = 'common-relation-item';
            itemEl.textContent = relation.text;
            
            // 点击加载这个常见关系
            itemEl.addEventListener('click', function() {
                currentRelations = [...relation.path];
                updateRelationChain();
                calculateRelationship();
            });
            
            commonRelationsContainer.appendChild(itemEl);
        }
    }
}); 